#include "mediawikiwindow.h"
#include "ui_mediawikiwindow.h"

#include <QMenu>
#include <QWebEngineHistory>
#include <QWebEngineProfile>
#include <QWebEngineSettings>
#include <QWebEngineView>
#include <deepwiki.h>
#include <httpclient.h>

#include <wiki/apkhub.h>
#include <wiki/archwiki.h>
#include <wiki/bbssparkstore.h>
#include <wiki/bilibiliarticle.h>
#include <wiki/bilibilivideo.h>
#include <wiki/bing.h>
#include <wiki/bmcxcpu.h>
#include <wiki/bmcxtools.h>
#include <wiki/cainiaojiaocheng.h>
#include <wiki/cmakedoc.h>
#include <wiki/cnblogs.h>
#include <wiki/csdnblog.h>
#include <wiki/deepinwiki.h>
#include <wiki/dev59.h>
#include <wiki/elecfans.h>
#include <wiki/github.h>
#include <wiki/goofish.h>
#include <wiki/govcn.h>
#include <wiki/gxde.h>
#include <wiki/jinbuguo.h>
#include <wiki/kr36.h>
#include <wiki/lerningx_in_yminutes.h>
#include <wiki/linaroresources.h>
#include <wiki/lingmo.h>
#include <wiki/linuxpkgsorg.h>
#include <wiki/metasoai.h>
#include <wiki/moegirl.h>
#include <wiki/opensourcehardwarehub.h>
#include <wiki/pastbin.h>
#include <wiki/poststelecomapi.h>
#include <wiki/qmlbook.h>
#include <wiki/rustcourse.h>
#include <wiki/rustcratesio.h>
#include <wiki/sdl.h>
#include <wiki/selfwiki.h>
#include <wiki/sourceforgeprojects.h>
#include <wiki/tailwindcssdoc.h>
#include <wiki/tencentdeveloper.h>
#include <wiki/typhoon.h>
#include <wiki/vbrid.h>
#include <wiki/xmakearchives.h>
#include <wiki/xmakedoc.h>
#include <wiki/zhihuzhidaai.h>

#include <wiki/github/discussions.h>

#include <wiki/linkwiki/linkwiki.h>

#include <wiki/searchwiki/searchwiki.h>

#include <dialog/wikicustomdialog.h>

#include <wiki/gitee/giteegxdeissues.h>

MediaWikiWindow::MediaWikiWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MediaWikiWindow)
{
    ui->setupUi(this);

    setWindowIcon(QIcon("://icon.png"));

//    setupUi(ui->frame);
//    setTitleLayout(ui->horizontalLayout);

    wikis.append(new Pastbin);
    wikis.append(new Bing(Bing::ZH));
    wikis.append(new Bing);
    wikis.append(new Dev59);
    wikis.append(new ItHome);
    wikis.append(new GiteeGxdeIssues);
    wikis.append(new SelfWiki);
    wikis.append(new Deepwiki);
    wikis.append(new QmlBook);
    wikis.append(new GitScmBook);
    wikis.append(new RustDoc);
    wikis.append(new RustCourse);
    wikis.append(new RustCratesIO);
    wikis.append(new ArchWikiLinks);
    wikis.append(new MoeGirl);
    wikis.append(new CaiNiaoJiaoCheng);
    wikis.append(new JinBuGuo);
    wikis.append(new CMakeDoc);
    wikis.append(new XMakeDoc);
    wikis.append(new XMakeArchives);
    wikis.append(new XMakeDiscussions);
    wikis.append(new DeepinWiki);
    wikis.append(new BBsSparkStore);
    wikis.append(new BmcxCpu);
    wikis.append(new BmcxTools);
    wikis.append(new BilibiliVideo);
    wikis.append(new BilibiliArticle);
    wikis.append(new VBrid);
    wikis.append(new GitHub);
    wikis.append(new SourceForgeProjects);
    wikis.append(new LerningX_IN_YMinutes);
    wikis.append(new ApkHub);
    wikis.append(new TencentDeveloper);
    wikis.append(new MetaSoAI);
    wikis.append(new ZhiHuZhiDaAI);
    wikis.append(new ZhiHu);
    wikis.append(new CnBlogs);
    wikis.append(new CsdnBlog);
    wikis.append(new StackRoom);
    wikis.append(new StackExchange);
    wikis.append(new PostsTelecom);
    wikis.append(new PostsTelecomAPI);
    wikis.append(new Kr36);
    wikis.append(new Kr36(Kr36::NewsFlashes));
    wikis.append(new GXDE);
    wikis.append(new Lingmo);
    wikis.append(new LingmoOSDiscussions);
    wikis.append(new GooFish);
    wikis.append(new LinuxPkgsOrg);
    wikis.append(new Typhoon);
    wikis.append(new ChinaGovLink);
    wikis.append(new Elecfans);
    wikis.append(new Elecfans(Elecfans::Electron));
    wikis.append(new SDL);
    wikis.append(new TailwindcssDoc);
    wikis.append(new TailwindcssDiscussions);
    wikis.append(new GovCN);
    wikis.append(new OpenSourceHardWareHub);
    wikis.append(new OpenSourceHardWareHub(OpenSourceHardWareHub::Article));
    wikis.append(new LinaroResources);
    wikis.append(new Taobao);
    wikis.append(new TerryW);
    wikis.append(new CsdnMiscLinksByCsdn);
    wikis.append(new MavenSearch);
    wikis.append(new TopeetVideoLinks);
    wikis.append(new TopeetCsdnLinksByCsdn);
    wikis.append(new TopeetBaijiahaoLinks);
    wikis.append(new ForgotFunVideoLinks);
    wikis.append(new ForgotFunOrg);
    wikis.append(new AndroidXiaoShuaiByZhiHu);

    for (int i = 0; i < wikis.length(); ++i) {
        auto wiki = wikis[i];
        ui->comboBox->addItem(wiki->name(), i);
    }

//    ui->comboBox->addItem("萌娘百科","https://mzh.moegirl.org.cn");
//    ui->comboBox->addItem("菜鸟教程","https://cainiaojiaocheng.com");
//    ui->comboBox->addItem("Eve百科","https://www.evebk.com");
    //ui->comboBox->addItem("MBA百科","https://wiki.mbalib.com/w");
//    ui->comboBox->addItem("维基百科","https://www.wikipedia.org/");

    ui->splitter->setSizes(QList<int>() << 150 << 400);
    ui->webEngineView->settings()->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture, false);
    ui->webEngineView->setOrigin_ui(this);

    connect(ui->webEngineView, &QWebEngineView::loadProgress, ui->progressBar, &QProgressBar::setValue);
    connect(ui->webEngineView, &QWebEngineView::loadFinished, this, [this](bool b){
        if (get_wiki()->once_reload()) {
            ui->webEngineView->reload();
        }
    });

    ui->btn_restore->hide();
}

MediaWikiWindow::~MediaWikiWindow()
{
    delete ui;
}

Wiki* MediaWikiWindow::get_wiki()
{
    int i = ui->comboBox->currentData().toInt();
    auto wiki = wikis.at(i);
    return wiki;
}

void MediaWikiWindow::reload_mediawiki_search(const QString &text)
{
    ui->listWidget->clear();

    if (get_wiki()->interactive_running()) {
        ui->btn_restore->show();
    }

    if (get_wiki()->forward_to_content()) {
        ui->splitter->widget(0)->setVisible(false);
        QListWidgetItem item;
        item.setText(text);
        on_listWidget_currentItemChanged(&item, nullptr);
        return;
    } else {
        ui->splitter->widget(0)->setVisible(true);
    }
    switch (get_wiki()->searchMode()) {
    case Wiki::Text:
        ui->listWidget->addItems(get_wiki()->searching(text));
        break;
    case Wiki::ListItem:
        foreach (auto var, get_wiki()->searching_item(text)) {
            ui->listWidget->addItem(var);
        }
        break;
    }
}

void MediaWikiWindow::do1(const QString &arg1)
{
    mediawiki_search_timer.stop();
    mediawiki_search_timer.disconnect();
    mediawiki_search_timer.setInterval(get_wiki()->searchDelay());

    connect(&mediawiki_search_timer, &QTimer::timeout, this, [this, arg1]()
    {
        mediawiki_search_timer.stop();
        reload_mediawiki_search(arg1);
    });

    mediawiki_search_timer.start();
}

void MediaWikiWindow::do2()
{
    ui->webEngineView->hide();
    ui->webEngineView->setParent(this);
    ui->groupBox_2->layout()->addWidget(ui->webEngineView);
    ui->webEngineView->show();
}

void MediaWikiWindow::on_lineEdit_textChanged(const QString &arg1)
{
    if (get_wiki()->searchMode()) {
        do1(arg1);
    }
}

void MediaWikiWindow::on_lineEdit_returnPressed()
{
    do1(ui->lineEdit->text());
}

void MediaWikiWindow::on_listWidget_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{

    if (current) {

        QString text = current->text();
        if (get_wiki()->interactive(text)) {
            reload_mediawiki_search(text);
            return;
        }

        QString content;
        if (get_wiki()->contentMode() != Wiki::NoContent) {
            switch (get_wiki()->searchMode()) {
            case Wiki::Text:
                content = get_wiki()->content(text);
                break;
            case Wiki::ListItem:
                content = get_wiki()->content_item(current);
                break;
            }
        } else {
            switch (get_wiki()->searchMode()) {
            case Wiki::Text:
                get_wiki()->content(text, ui->webEngineView);
                break;
            case Wiki::ListItem:
                get_wiki()->content_item(current, ui->webEngineView);
                break;
            }
            return;
        }

        switch (get_wiki()->contentMode()) {
        case Wiki::Url:
            ui->webEngineView->setUrl(QUrl::fromUserInput(content));
            emit onMessageSignal(content);
            break;
        case Wiki::Content:
            ui->webEngineView->setHtml(content);
        case Wiki::UrlOrContent:
            if (content.startsWith("http")) {
                ui->webEngineView->load(QUrl::fromUserInput(content));
                emit onMessageSignal(content);
            } else {
                ui->webEngineView->setHtml(content);
            }
            break;
        default:
            break;
        }
    }
}


void MediaWikiWindow::on_comboBox_currentIndexChanged(int index)
{
    if (get_wiki()->autoLoad()) {
        reload_mediawiki_search("");
    }
    if (get_wiki()->autoLoadFirst()) {
        on_listWidget_currentItemChanged(ui->listWidget->item(0), nullptr);
    }
}

void MediaWikiWindow::on_pushButton_clicked()
{
    do1(ui->lineEdit->text());
}


void MediaWikiWindow::keyPressEvent(QKeyEvent *event)
{
    if (event->modifiers() == Qt::AltModifier && event->key() == Qt::Key_Left) {
        QWebEngineHistory *his = ui->webEngineView->history();
        if (his && his->canGoBack() && his->backItem().url().matches(QUrl("about:blank"), QUrl::None)) {
            return;
        }
        ui->webEngineView->back();
    }

    if (event->modifiers() == Qt::AltModifier && event->key() == Qt::Key_Right) {
        ui->webEngineView->forward();
    }

    if (event->key() == Qt::Key_F12) { // 全屏
        ui->webEngineView->showMax();
        return;
    }

    if (event->key() == Qt::Key_F11) { // 还原
        ui->webEngineView->showOrigin();
        return;
    }
    QWidget::keyPressEvent(event);
}

void MediaWikiWindow::on_btn_restore_clicked()
{
    get_wiki()->interactive_restore();
    ui->lineEdit->text();
    on_lineEdit_textChanged("");
    ui->btn_restore->hide();
}

void MediaWikiWindow::on_MediaWikiWindow_customContextMenuRequested(const QPoint &pos)
{
    QMenu menu;
    menu.addAction(ui->action_config_dataset);
    menu.exec(QCursor::pos());
}

void MediaWikiWindow::on_frame_customContextMenuRequested(const QPoint &pos)
{
    QMenu menu;
    menu.addAction(ui->action_config_dataset);
    menu.exec(QCursor::pos());
}

void MediaWikiWindow::on_action_config_dataset_triggered()
{
    WikiCustomDialog dialog;
    dialog.setWindowTitle("数据集自定义");
    dialog.exec();
}


